﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.IO;
using PMKB_DAL;
using PMKB_Repository;
using PagedList;

namespace Plugin_DisplayFavorites
{
    public class Favorites
    {
        readonly string FilePath;
        readonly string Connection;
        public Favorites(string filePath, string connection)
        {
            FilePath = filePath;
            Connection = connection;
        }
        public I_Link_List favoritesList;
        public IPagedList<I_Link> linkSearch;
        private long[] ids
        {
            get
            {
                if (!File.Exists(FilePath))
                    return null;
                var str = File.ReadAllText(FilePath);
                var ids = str.Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                var idLong = new long[ids.Length];
                int i = 0;
                foreach (var item in ids)
                {
                    idLong[i++] = long.Parse(item);
                }
                return idLong;
            }
        }
        public virtual void LoadExisting()
        {
            favoritesList = new I_Link_List();
            var idLong = ids;
            if (idLong == null)
                return;
           
            using (Link_List ll = new Link_List(Connection))
            {                
                ll.LoadFromDB.LoadFindIDsColumn_LinkID(idLong);
                ll.Sort(new Link_Comparer(Link_List.FieldNames.LinkName, true));
                favoritesList = ll;
            }

        }

        public virtual void LoadLinks(int PageNumber,int PageSize, string search)
        {
            clsLoadLinks ll = new clsLoadLinks();
            ll.ConnectionName = Connection;
            linkSearch = ll.LoadLinksSearch(PageNumber, PageSize, Link_List.FieldNames.LinkName, true);

        }

        internal void AddLink(long id)
        {
            File.AppendAllText(FilePath, id + ";");
        }

        internal void RemoveLink(long id)
        {
            var idsLong = ids;
            if (idsLong == null)
                return;

            var idarr=idsLong.Where(item=>item !=id).Select(item=>item ).ToArray();
            File.WriteAllText(FilePath, string.Join(";", idarr));

        }
    }
}
